package liuch.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 17101651
 * @ClassName ReadWriteLockTest
 * @Description 读写锁测试案例
 * Thread-0读操作
 * Thread-1读操作
 * Thread-1读操作完毕
 * Thread-0读操作完毕
 * Thread-0写操作
 * Thread-0写操作完毕
 * Thread-1写操作
 * Thread-1写操作完毕
 * 结果：读操作可以并行，写操作不能并行
 * @data 2018年07月17日
 */
public class ReadWriteLockTest {
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        final ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockTest.read();
                readWriteLockTest.write();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockTest.read();
                readWriteLockTest.write();
            }
        }).start();
    }

    /**
     * 功能描述: 添加读锁模拟读操作<br>
     *
     * @author 17101651
     */
    public void read() {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读操作");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "读操作完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    /**
     * 功能描述:添加写锁模拟写操作 <br>
     *
     * @author 17101651
     */
    public void write() {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写操作");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "写操作完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}

